package org.cuatrovientos.struts;



import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;


/**
 * implementation of CarDAOInterface
 * @author Pablo Guerrero
 *
 */
public class CarDAO implements CarDAOInterface {

	private Session session;
	

	/**
	 * default constructor
	 */
	public CarDAO () {
		session = HibernateSession.getSession();
	}
	
	/** 
	 * selects one car by Id
	 * @param id
	 * @return car
	 */
	public Car selectById(int id) {
	    Car car = (Car) session.get(Car.class, id);
	    return car;
	}

	/**
	 * retrieves all cars from the database
	 * @return List of cars
	 */
	public List<Car> selectAll() {
	 
	    List<Car> cars = session.createQuery("from Car").list();
	    return cars;
	}
	
	/**
	 * retrieves all cars from db
	 * @return List of cars
	 */
	public int selectAllCount() {
	 
	    List<Car> cars = session.createQuery("from Car").list();

	    return cars.size();
	}

	/**
	 * This method inserts a new car in database
	 * retrieves generated id and sets to car instance
	 * @param car
	 */
	public void insert(Car car) {
	    session.beginTransaction();
	 
	    Integer id = (Integer) session.save(car);
	    car.setId(id);
	         
	    session.getTransaction().commit();
	         
	}

	/**
	 * This method is in charge of update a car
	 * @param car to update
	 */
	public void update(Car car) {
		 
		    session.beginTransaction();
		 
		    session.merge(car);
		 
		    session.getTransaction().commit();
		 
	}

	/**
	 * This method delete given product
	 * @param car to delete
	 */
	public void delete(Car car) {
	    
	    session.beginTransaction();
	    
	    session.delete(car);
	 
	    session.getTransaction().commit();
	 
	}

	/**
	 * This method is in charge of saving or updating a car
	 * @param car
	 */
	public void saveOrUpdate(Car car) {
	    session.beginTransaction();
	    
	    session.saveOrUpdate(car);
	 
	    session.getTransaction().commit();
		
	}

}
